/*
 * @Author: szx
 * @Date: 2022-03-30 13:54:49
 * @LastEditTime: 2022-03-30 14:07:38
 * @Description:
 * @FilePath: \leetcode\剑指offerII\002\002.js
 */
/**
 * @param {string} a
 * @param {string} b
 * @return {string}
 */
var addBinary = function (a, b) {
    let flag = 0;
    if (a.length < b.length) [a, b] = [b, a];
    let i = a.length - 1,
        j = b.length - 1;
    const res = [];
    while (j >= 0) {
        const c = +a[i];
        const d = +b[j];
        if (c ^ d) {
            if (flag) res.push(0);
            else res.push(1);
        } else {
            if (flag) res.push(1);
            else res.push(0);
            flag = c && d;
        }
        i--;
        j--;
    }
    while (i >= 0) {
        const c = +a[i];
        if (flag) {
            if (c) {
                res.push(0);
            } else {
                res.push(1);
                flag = 0;
            }
        } else {
            res.push(c);
        }
        i--;
    }
    if (flag) res.push(1);
    return res.reverse().join('');
};
console.log(addBinary('1', '111'));
console.log(addBinary('11', '10'));
console.log(addBinary('1010', '1011'));
